package com.zjlanyun.erp.interior.production;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aihook.alertview.library.AlertView;
import com.aihook.alertview.library.OnItemClickListener;
import com.alibaba.fastjson.JSON;
import com.yolanda.nohttp.rest.Response;
import com.zjlanyun.erp.Data;
import com.zjlanyun.erp.R;
import com.zjlanyun.erp.interior.CommonList;
import com.zjlanyun.erp.network.WebApi;
import com.zjlanyun.erp.nohttp.HttpRequest;
import com.zjlanyun.erp.nohttp.SimpleHttpListener;
import com.zjlanyun.erp.rfid.m10.u8.activity.OutPowerActivity;
import com.zjlanyun.erp.utils.StringUtils;
import com.zjlanyun.erp.utils.Toastor;
import com.zjlanyun.erp.utils.ViewUtil;
import com.zjlanyun.erp.view.BaseRFIDActivity;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.OnClick;

public class LingliaoBind extends BaseRFIDActivity {

    @Bind(R.id.tv_result) TextView tv_result;
    @Bind(R.id.tv_epc) TextView tv_epc;
    @Bind(R.id.tv_FGongxuName) TextView tv_FGongxuName;
    @Bind(R.id.tv_status) TextView tv_status;
    @Bind(R.id.tv_FName) TextView tv_FName;
    @Bind(R.id.tv_FQty) TextView tv_FQty;
    @Bind(R.id.tv_FCLName) TextView tv_FCLName;
    @Bind(R.id.tv_FNumber) TextView tv_FNumber;
    @Bind(R.id.tv_FModel) TextView tv_FModel;
    @Bind(R.id.ll_submit) LinearLayout ll_submit;
    @Bind(R.id.tv_FAuxPropID) TextView tv_FAuxPropID;
    @Bind(R.id.tv_FMacNO) TextView tv_FMacNO;
    @Bind(R.id.tv_Fmotype) TextView tv_Fmotype;
    @Bind(R.id.tv_FWidth) TextView tv_FWidth;
    @Bind(R.id.tv_FCLNumber) TextView tv_FCLNumber;
    @Bind(R.id.ll_cancel) LinearLayout ll_cancel;
    @Bind(R.id.cb_cancel) CheckBox cb_cancel;

    private boolean scaning = false;
    private String apiUrl = "";
    private ArrayList<HashMap<String, Object>> mBomList;
    private int FItemID = 0;
    private int FAuxPropID = 0;  //生产任务单ID
    private String planMacNO = ""; //生产加工单中的机台号

    public static final int REQUESTCODE_SELECTPRO = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.lingliao_bind);
        initBaseView();
        initView();
    }

    private void initView() {
        apiUrl = WebApi.production();
        title.setText("领料备货");
        ll_submit.setVisibility(View.VISIBLE);

        ll_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!tv_epc.getText().toString().equals("")) {
                    new AlertView("提示", "有未提交的数据，确定退出当前页吗？", "取消", new String[]{"确定"}, null, mContext, AlertView.Style.AlertDialog, new OnItemClickListener() {
                        @Override
                        public void onItemClick(Object o, int position) {
                            if (position == 0) {
                                finish();
                            }
                        }
                    }).show();
                } else {
                    finish();
                }
            }
        });
    }

    /**
     * 开始扫描
     */
    public void startScan() {
        tv_status.setText("盘询开始");
        scanNumber = 1;
        scaning = true;
        super.startScan();
    }

    /**
     * 停止扫描
     */
    public void stopScan() {
        tv_status.setText("盘询结束");
        scaning = false;
        super.stopScan();
    }

    public void refreshText() {
        super.refreshText();
        tv_result.setText(String.format("扫描到:%d个", m_curInventoryBuffer.lsTagList.size()));
        if (m_curInventoryBuffer.lsTagList.size() > 0) {
            String strEPC = m_curInventoryBuffer.lsTagList.get(0).getStrEPC().replace(" ", "");
            //材料
            getLingliaoInfo(strEPC);
        }
    }

    /**
     * 获取材料信息
     */
    private void getLingliaoInfo(String epc) {
        HashMap<String, Object> param = new HashMap<>();
        param.put("epc", epc);
        param.put("FActionFlag", "beihuo");
        HttpRequest client = new HttpRequest(mContext, apiUrl, "getLingliaoInfo", JSON.toJSONString(param), true, true);
        client.send(new SimpleHttpListener<JSONObject>() {
            @Override
            public void onSucceed(int what, Response<JSONObject> response) {
                JSONObject data = response.get().optJSONObject("data");
                tv_epc.setText(data.optString("epc"));
                tv_FName.setText(data.optString("FName"));
                tv_FQty.setText(String.valueOf(data.optDouble("FCLQty")));
                tv_FCLName.setText(data.optString("FCLName"));
                tv_FNumber.setText(data.optString("FNumber"));
                tv_FModel.setText(data.optString("FModel"));
                planMacNO = data.optString("FMacNO");
                tv_FMacNO.setText(data.optString("FMacNO"));
                tv_Fmotype.setText(data.optString("Fmotype"));
                tv_FWidth.setText(data.optString("FWidth"));
                tv_FCLNumber.setText(data.optString("FCLNumber"));
                tv_FGongxuName.setText(data.optString("FGongxuName"));

                if (data.optInt("FHeadExtInt03") > 0) {
                    ll_cancel.setVisibility(View.VISIBLE);
                    cb_cancel.setChecked(true);
                    Toastor.getInstance().showLongToast("该产品已经设置为备货，再次提交取消备货");
                } else {
                    ll_cancel.setVisibility(View.GONE);
                    cb_cancel.setChecked(false);
                }

                FItemID = data.optInt("FItemID");
                FAuxPropID = data.optInt("FAuxPropID");
                tv_FAuxPropID.setText(String.valueOf(data.optInt("FAuxPropID")));

                mBomList = new ArrayList<>();
                JSONArray bom = data.optJSONArray("bom");
                for (int i = 0; i < bom.length(); i++) {
                    JSONObject item = bom.optJSONObject(i);
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("FName", item.optString("FName"));
                    map.put("FItemID", item.optString("FItemID"));
                    map.put("FNumber", item.optString("FNumber"));
                    map.put("FModel", item.optString("FModel"));
                    map.put("FAuxPropID", item.optInt("FAuxPropID"));
                    map.put("FMacSpeed", item.optString("FMacSpeed"));
                    map.put("FMacNO", item.optString("FMacNO"));
                    map.put("Fmotype", item.optString("Fmotype"));
                    map.put("FDate", item.optString("FDate"));
                    map.put("FBeihuoQty", "已备：" + item.optString("FBeihuoQty"));
                    mBomList.add(map);
                }
                if (data.optInt("FCLItemID") == 0) {
                    Toastor.getInstance().showShortToast("该卡没有绑定任何产品");
                }
            }

            @Override
            public void onError(int what, Response<JSONObject> response) {
                clear();
                super.onError(what, response);
            }
        });
    }

    /**
     * 选择产品
     */
    @OnClick(R.id.btn_selectpro)
    public void select_pro() {
        if (mBomList != null) {
            Bundle bundle = new Bundle();
            bundle.putString("title", "选择产品");
            bundle.putIntArray("layout", new int[]{R.id.tv1, R.id.tv2, R.id.tv3, R.id.tv4, R.id.tv6, R.id.tv7, R.id.tv9});
            bundle.putStringArray("field", new String[]{"FName", "Fmotype", "FAuxPropID", "FNumber", "FDate", "FModel", "FBeihuoQty"});
            bundle.putString("list", JSON.toJSONString(mBomList));
            bundle.putString("action", "common");
            Intent intent = new Intent(mContext, CommonList.class);
            intent.putExtras(bundle);
            startActivityForResult(intent, REQUESTCODE_SELECTPRO);
        } else {
            Toastor.getInstance().showShortToast("无产品数据，请先扫卡");
        }
    }

    /**
     * 提交
     */
    @OnClick(R.id.ll_submit)
    public void postLoading() {
        ViewUtil.hideInputMethod(mContext, ll_back);
        if (tv_epc.getText().toString().equals("")) {
            Toastor.getInstance().showShortToast("请先扫卡");
            return;
        } else if (FItemID == 0) {
            Toastor.getInstance().showShortToast("请选择产品");
            return;
        } else if (FAuxPropID == 0) {
            Toastor.getInstance().showShortToast("加工单单号不能为0");
            return;
        }
        send();
    }

    private void send() {
        HashMap<String, Object> param = new HashMap<>();
        param.put("epc", tv_epc.getText().toString());
        param.put("FAuxPropID", FAuxPropID);
        if (cb_cancel.isChecked()) {
            param.put("FActionFlag", "quxiaobeihuo");
        } else {
            param.put("FActionFlag", "beihuo");
        }
        HttpRequest client = new HttpRequest(mContext, apiUrl, "postLingliao", JSON.toJSONString(param), true, true);
        client.send(new SimpleHttpListener<JSONObject>() {
            @Override
            public void onSucceed(int what, Response<JSONObject> response) {
                clear();
                Toastor.getInstance().showShortToast(R.string.submit_success);
                ll_cancel.setVisibility(View.GONE);
            }
        });
    }

    /**
     * 清空数据
     */
    private void clear() {
        tv_epc.setText("");
        tv_FCLName.setText("");
        tv_FQty.setText("");
        tv_FName.setText("");
        tv_FNumber.setText("");
        tv_FModel.setText("");
        tv_FAuxPropID.setText("");
        tv_FMacNO.setText("");
        tv_Fmotype.setText("");
        tv_FWidth.setText("");
        tv_FCLNumber.setText("");
        tv_FGongxuName.setText("");
        FItemID = 0;
        FAuxPropID = 0;
        mBomList = null;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == 80 && Build.MODEL.equals(Data.RFID_DEVICE)) {
            if (scaning) {
                stopScan();
            } else {
                startScan();
            }
            return false;
        } else if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (!tv_epc.getText().toString().equals("")) {
                new AlertView("提示", "有未提交的数据，确定退出当前页吗？", "取消", new String[]{"确定"}, null, mContext, AlertView.Style.AlertDialog, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        if (position == 0) {
                            finish();
                        }
                    }
                }).show();
                return false;
            }
        } else if ((keyCode == 131 && Build.MODEL.equals(Data.RFID_DEVICE)) || (keyCode == 132 && Build.MODEL.equals(Data.RFID_DEVICE)) || (keyCode == 133 && Build.MODEL.equals(Data.RFID_DEVICE))) {
            Intent intent = new Intent(mContext, OutPowerActivity.class);
            intent.putExtra("from", "RFID" + className);
            startActivity(intent);
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUESTCODE_SELECTPRO && resultCode == RESULT_OK && data != null) {
            Bundle bundle = data.getExtras();
            int p = bundle.getInt("position");
            tv_FName.setText(mBomList.get(p).get("FName").toString());
            tv_FNumber.setText(mBomList.get(p).get("FNumber").toString());
            tv_FModel.setText(mBomList.get(p).get("FModel").toString());
            FItemID = Integer.valueOf(mBomList.get(p).get("FItemID").toString());
            FAuxPropID = StringUtils.toInt(mBomList.get(p).get("FAuxPropID").toString(), 0);
            tv_FAuxPropID.setText(mBomList.get(p).get("FAuxPropID").toString());
            tv_FMacNO.setText(mBomList.get(p).get("FMacNO").toString());
            planMacNO = mBomList.get(p).get("FMacNO").toString();
            tv_Fmotype.setText(mBomList.get(p).get("Fmotype").toString());
        }
    }
}
